<!--班车基础点名信息页-->
<template>
    <div style="height: 100%;">
        <m-page-list
                :option="option"
                :page="page"
                :total="total"
                :table-data="tableData"
                :table-loading="tableLoading"
                :page-loading="pageLoading"
                v-model:value="query"
                @h-btn-click="hBtnClick"
                @col-btn-click="colBtnClick"
                @search-data="searchData"
        >
            <!--导入-->
            <template #import>
                <el-upload
                        ref="uploadRef"
                        class="upload-wrap"
                        action=""
                        accept=".xlsx,.xls"
                        :auto-upload="false"
                        :show-file-list="false"
                        :on-change="importData"
                >
                    <el-button type="primary" >导入</el-button>
                </el-upload>
            </template>
        </m-page-list>
        <!--新增弹窗-->
        <m-dialog-form ref="dialogRef" :data="dialogData" v-model:show="dialogShow" :option="dialogOption" @confirm="dialogConfirm" ></m-dialog-form>

        <!--查看详细弹窗-->
        <el-dialog class="dialog-wrap" v-model="detailShow" width="95%" :title="detailTitle" :close-on-click-modal="false" draggable align-center destroy-on-close>
            <shuttle-detail style="height: 90vh;" class="dtl-wrap" :data="shuttleData" @save="getDataList"></shuttle-detail>
        </el-dialog>

        <!--生成基础班车录入参数弹窗-->
        <m-dialog-form ref="generateDialogRef" :data="generateDialogOpt.data" v-model:show="showGenerateDialog" :option="generateDialogOpt" @confirm="generateConfirm" ></m-dialog-form>
        <!--生成每日班车录入参数弹窗-->
        <m-dialog-form ref="generateDailyDialogRef" :data="generateDailyDialogOpt.data" v-model:show="showGenerateDailyDialog" :option="generateDailyDialogOpt" @confirm="generateDailyConfirm" ></m-dialog-form>

        <!--生成每日点名进度条-->
        <!--<el-dialog v-model="showProgress" :title="progressTitle" center width="400" align-center :show-close="false" :close-on-click-modal="false">
            <el-progress :percentage="percentage" :text-inside="true" :stroke-width="15" striped :striped-flow="stripedFlow" :duration="duration"/>
            <div v-show="errmsg.length" class="errmsg">
                <div v-for="item in errmsg">{{item}}</div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-show="endError" type="primary" @click="showProgress = false">关闭</el-button>

                    <div v-show="isShowStopBtn">
                        <el-button v-show="!isUploadStop" type="primary" @click="stopUpload">停止</el-button>
                        <el-button v-show="isUploadStop" type="default" @click="showProgress = false">关闭</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>-->
        <m-progress ref="progressRef">
            <template #footer>
                <div v-show="isShowStopBtn">
                    <el-button v-show="!isEachStop" type="primary" @click="stopUpload">停止</el-button>
                    <el-button v-show="isEachStop" type="default" @click="progressRef.close()">关闭</el-button>
                </div>
            </template>
        </m-progress>

        <div class="table-dialog-wrap">
        <!--照片未上传统计表格-->
        <el-dialog v-model="showNoUploadTable" title="照片未上传统计">
            <div class="table-dialog-header">
                <el-button type="primary" @click="batchUploadPic">批量上传照片</el-button>
            </div>
                <el-table
                        ref="tRef"
                        class="table-auto"
                        height="500px"
                        border
                        :data="noUploadTableData"
                        highlight-current-row
                        :tooltip-options="{placement: 'right'}"
                        empty-text="暂无数据"
                        :summary-method="getSummaries"
                        show-summary
                        v-loading="noUploadTableLoading"
                >
                    <el-table-column
                            v-for="item in noUploadTableCols"
                            :prop="item.prop" :label="item.label"
                            :sortable="item.sortable"
                    ></el-table-column>
                    <el-table-column fixed="right" label="操作" width="100" >
                        <template #default="scope">
                            <el-button link type="primary" @click.stop="uploadPhotos(scope)">上传照片</el-button>
                        </template>
                    </el-table-column>
                </el-table>
        </el-dialog>
    </div>

        <!--批量上传照片-->
        <m-dialog-form ref="uploadDialogRef" :data="uploadDialogOpt.data" v-model:show="showUploadDialog" :option="uploadDialogOpt" @confirm="uploadConfirm" ></m-dialog-form>

    </div>
</template>

<script setup>

  import {useRouter} from 'vue-router'
  import {ref,reactive,computed,nextTick,h} from 'vue'
  //组件
  import MPageList from '@/components/PageList'
  import MDialogForm from '@/components/DialogForm/DialogForm'
  import ShuttleDetail from './RollcallBasicShuttleDetail'
  import MProgress from '@/components/common/Progress/Progress'

  //请求
  import {getRollCallBasicShuttleData, addRollCallBasicShuttleData,editRollCallBasicShuttleData,delRollCallBasicShuttleData,
    generateRollCallBasicShuttleByDate,generateRollCallBasicShuttleFromShuttleSeat,
    getRole,getEmployeeInf,getNotUploadPicCount,getParameter,uploadAliyunFacePic} from '@/request/api/basicData'

  import {usePageList} from "../../composables/pageList";
  import {refOpt} from "../const";
  import {crtTimeFtt} from "../../utils/utils";
  import {handleUploadChange} from "./importBasicShuttle";

  const router = useRouter();

  let opts = {
    auth_id: 'all_rollcall_shuttle',
    getApi: getRollCallBasicShuttleData,addApi:addRollCallBasicShuttleData,editApi:editRollCallBasicShuttleData,delApi:delRollCallBasicShuttleData,
    idKey: 'row_id'
  };
  let {option,page,total,pageLoading,tableLoading,tableData,query,dialogRef,dialogShow,dialogData,dialogOption,
    hBtnClick,colBtnClick,searchData,getDataList,dialogConfirm} = usePageList(opts);

  /* 顶部标题导航 */
  /*option.titleList = [
    {name: '班车基础点名信息',path: '/rollcallBasicShuttle'},
    {name: '班车基础点名座位信息',path: '/rollcallBasicShuttleSeat'},
  ]*/
  /*查询条件*/
  option.conditions = [
    {label: '有效日期',field_id: ['effective_date_begin','effective_date_end'], type: 'daterange',length: 'YYYY-MM-DD',col: 8},
    {field_id: 'shuttle_no', label: '点名班车号',type: 'text',col: 8},
    {field_id: 'shuttle_name', label: '点名班车名',type: 'text',col: 8},
    {label: '班车类型',field_id: 'shuttle_type',type: 'picklist',options: [{name: '车站客运班车',id: '车站客运班车'},{name: '定制',id: '定制'},],col: 12},
    {...refOpt.shuttle_direction_name,field_id: 'direction',label: '方向',col:12, valueKey: [{'direction': 'shuttle_direction_name'}] ,rewriteInput: true,},
  ];
  /*表格列*/
  option.cols = [
    {prop: 'shuttle_no', label: '点名班车号',},
    {prop: 'shuttle_name', label: '点名班车名',},
    {prop: 'shuttle_type', label: '班车类型',},
    {prop: 'no_upload_num', label: '未上传照片数量',total:true},
    {prop: 'effective_date_begin', label: '有效日期起',},
    {prop: 'effective_date_end', label: '有效日期止',},
    {prop: 'direction',label: '方向' },
    {prop: 'shuttle_seat_id',label: '售票班车座位表号' },
    {prop: 'shuttle_seat_name',label: '售票班车座位表名' },
    {prop: 'is_used',label: '启用标识', type: 'bool'},
    {prop: 'first_departure_time',label: '始发时间'},
    {prop: 'shuttles',label: '售票班车名串'},
    {prop: 'line_name',label: '线路名'},
    {prop: 'first_stop_name',label: '起点'},
    {prop: 'last_stop_name',label: '终点'},
    {prop: 'seat_count',label: '客座数'},
    {prop: 'vehicle_no',label: '车牌号码'},
    {prop: 'driver_no',label: '司机工号'},
    {prop: 'driver_name',label: '司机姓名'},
    {prop: 'caretaker_no',label: '照管员号'},
    {prop: 'caretaker_name',label: '照管员名'},
    {prop: 'caretaker_no_2',label: '照管员号2'},
    {prop: 'caretaker_name_2',label: '照管员名2'},
    {prop: 'caretaker_no_3',label: '照管员号3'},
    {prop: 'caretaker_name_3',label: '照管员名3'},
    {prop: 'rollcall_admin_no',label: '点名管理人号'},
    {prop: 'rollcall_admin_name',label: '点名管理人名'},
    {prop: 'rollcall_admin_no_2',label: '点名管理人号2'},
    {prop: 'rollcall_admin_name_2',label: '点名管理人名2'},
    {prop: 'rollcall_admin_no_3',label: '点名管理人号3'},
    {prop: 'rollcall_admin_name_3',label: '点名管理人名3'},
    {prop: 'remarks',label: '备注'},
    {prop: 'input_id',label: '录入员号' },
    {prop: 'input_name',label: '录入员名' },
    {prop: 'input_time',label: '录入时间' },
    {prop: 'modify_id',label: '修改员号' },
    {prop: 'modify_name',label: '修改员名' },
    {prop: 'modify_time',label: '修改时间' },
  ];
  option.colBtns.shift();
  option.colBtns.unshift(
    {title: '查看',id: 'detail',type: 'primary',event: checkDetail},
    );



  /*顶部按钮*/
  option.hLBtns.push(
    {title: '生成点名班车',type: 'primary',event: () =>{showGenerateDialog.value = true}},
    {title: '生成每日点名班车',type: 'primary',event: () =>{showGenerateDailyDialog.value = true}},
    {useSlot: true,slotName: 'import'},
    // {title: '批量上传照片',type: 'primary',event: () =>{batchUploadPic() }},
  );
  option.hRBtns.unshift(
    {title: '照片未上传统计',type: 'primary',event: () => { getNoUploadData() }},
  );

  /*新增编辑弹窗字段*/
  dialogOption.fieldList = [
    {field_id: 'shuttle_no', label: '点名班车号',type: 'text',col:2,required: true},
    {field_id: 'shuttle_name', label: '点名班车名',type: 'text',col:2,required: true},
    {field_id: 'effective_date_begin',label: '有效日期起',type: 'date',dateFormat: 'YYYY-MM-DD',col: 2 },
    {field_id: 'effective_date_end',label: '有效日期止',type: 'date',dateFormat: 'YYYY-MM-DD',col: 2 },
    {...refOpt.shuttle_seat_id,col:2, label: '售票班车座位表号'},
    {...refOpt.shuttle_seat_name,col:2, label: '售票班车座位表名'},
    {field_id: 'shuttle_type',label: '班车类型',type: 'picklist',options: [{label:'车站客运班车',value:'车站客运班车'},{label:'定制',value:'定制'}],defaultValue:'车站客运班车',col: 2 },
    {...refOpt.shuttle_direction_name,field_id: 'direction',label: '方向',col:2, valueKey: [{'direction': 'shuttle_direction_name'}] ,},
    {field_id: 'is_used',label: '启用标识', type: 'bool',col:2,},
    {field_id: 'first_departure_time',label: '始发时间',type: 'time',col:2,},
    {field_id: 'shuttles',label: '售票班车名串',type: 'text',col:2,},
    {field_id: 'line_name',label: '线路名',type: 'text',col:2},
    {field_id: 'first_stop_name',label: '起点',type: 'text',col:2},
    {field_id: 'last_stop_name',label: '终点',type: 'text',col:2},
    {field_id: 'seat_count',label: '客座数',type: 'number',col:2,},
    {field_id: 'vehicle_no',label: '车牌号码',type: 'text',col:2,},
    {...refOpt.driver_no,col:2,},
    {...refOpt.driver_name,col:2,},
    {...refOpt.caretaker_no,col:2,},
    {...refOpt.caretaker_name,col:2,},
    {...refOpt.caretaker_no, label: '照管员号2',field_id: 'caretaker_no_2',col:2},
    {...refOpt.caretaker_name, label: '照管员名2',field_id: 'caretaker_name_2',col:2, valueKey: [{'caretaker_no_2': 'caretaker_no'},{'caretaker_name_2': 'caretaker_name'}]},
    {...refOpt.caretaker_no, label: '照管员号3',field_id: 'caretaker_no_3',col:2},
    {...refOpt.caretaker_name, label: '照管员名3',field_id: 'caretaker_name_3',col:2, valueKey: [{'caretaker_no_3': 'caretaker_no'},{'caretaker_name_3': 'caretaker_name'}]},
    {...refOpt.rollcall_admin_no,col:2,},
    {...refOpt.rollcall_admin_name,col:2,},
    {...refOpt.rollcall_admin_no, label: '点名管理人号2',field_id: 'rollcall_admin_no_2',col:2,},
    {...refOpt.rollcall_admin_name, label: '点名管理人名2',field_id: 'rollcall_admin_name_2',col:2, valueKey: [{'rollcall_admin_no_2': 'rollcall_admin_no'},{'rollcall_admin_name_2': 'rollcall_admin_name'}],},
    {...refOpt.rollcall_admin_no, label: '点名管理人号3',field_id: 'rollcall_admin_no_3',col:2,},
    {...refOpt.rollcall_admin_name, label: '点名管理人名3',field_id: 'rollcall_admin_name_3',col:2, valueKey: [{'rollcall_admin_no_3': 'rollcall_admin_no'},{'rollcall_admin_name_3': 'rollcall_admin_name'}],},
    {field_id: 'remarks',label: '备注',type: 'text',col:4,},
  ];
  function checkSeat(scope) {
    router.push({
      path:'/rollcallBasicShuttleSeat',query: {shuttle_id: scope.row.shuttle_no}
    })
  }

  /*----------------查询详细弹窗-----------------*/
  let detailShow = ref(false),
    shuttleData = ref({}),
    detailTitle = ref('查看');
  function checkDetail(scope,id) {
    detailShow.value = true;
    shuttleData.value = scope.row;
    detailTitle.value = scope.row.shuttle_name;
  }

  /*-------------------生成点名班车-------------------*/
  const generateDialogOpt = reactive({
        title: '生成点名班车',
        fieldList: [
          {field_id: 'type',label: '生成类型',col: 3,type: 'radio',options: [{name:'生成全部',id: 'all'},{name: '指定销售班车座位表',id: 'seat'}]},
          {field_id: 'effective_date_begin',label: '有效日期起',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3 ,required: true },
          {field_id: 'effective_date_end',label: '有效日期止',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3,required: true  },
          {field_id: 'generate_mode',label: '生成模式',type: 'radio',col: 3 ,options: [{name:'只新增',id: '1'},{name: '只修改',id: '2'},{name: '新增和修改',id: '3'}],required: true},
        ],
        data: {type: 'all'},
        bindChange: function (data) {
        //  生成类型变化，更新弹窗字段
        if (data.type === 'all'){
          generateDialogOpt.fieldList = [
            {field_id: 'type',label: '生成类型',col: 3,type: 'radio',options: [{name:'生成全部',id: 'all'},{name: '指定销售班车座位表',id: 'seat'}]},
            {field_id: 'effective_date_begin',label: '有效日期起',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3,required: true },
            {field_id: 'effective_date_end',label: '有效日期止',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3 ,required: true},
            {field_id: 'generate_mode',label: '生成模式',type: 'radio',col: 3 ,options: [{name:'只新增',id: '1'},{name: '只修改',id: '2'},{name: '新增和修改',id: '3'}],required: true},
          ]
        }else {
          generateDialogOpt.fieldList = [
            {field_id: 'type',label: '生成类型',col: 3,type: 'radio',options: [{name:'生成全部',id: 'all'},{name: '指定销售班车座位表',id: 'seat'}]},
            {field_id: 'effective_date_begin',label: '有效日期起',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3 ,required: true },
            {field_id: 'effective_date_end',label: '有效日期止',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3,required: true  },
            {...refOpt.shuttle_seat_id,col:3, label: '售票班车座位表号',required: true},
            {...refOpt.shuttle_seat_name,col:3, label: '售票班车座位表名',required: true},
            {field_id: 'rollcall_shuttle_no', label: '点名班车号',type: 'text',col:3},
            {field_id: 'rollcall_shuttle_name', label: '点名班车名',type: 'text',col:3},
            {field_id: 'generate_mode',label: '生成模式',type: 'radio',col: 3 ,options: [{name:'只新增',id: '1'},{name: '只修改',id: '2'},{name: '新增和修改',id: '3'}],required: true},
          ]

        }
      }
    }),
    showGenerateDialog = ref(false),
    generateDialogRef = ref(null);
  function generateConfirm(obj) {
    let {type,effective_date_begin,effective_date_end,shuttle_seat_id,shuttle_seat_name,rollcall_shuttle_no,rollcall_shuttle_name,generate_mode} = obj.data,
      post = {};
    if (type === 'all'){
      post = {effective_date_begin,effective_date_end,generate_mode}
    }else {
      rollcall_shuttle_no = rollcall_shuttle_no || shuttle_seat_id;
      rollcall_shuttle_name = rollcall_shuttle_name || shuttle_seat_name;
      post = {shuttle_seat_id, rollcall_shuttle_no, rollcall_shuttle_name, effective_date_begin, effective_date_end,generate_mode};
    }
    showGenerateDialog.value = false;
    pageLoading.value = true;
    generateRollCallBasicShuttleFromShuttleSeat(post).then(res =>{
      pageLoading.value = false;
      if (res.errcode != 0 ) return;
      ElMessage({type: 'success',message: '生成成功'});

    });
  }


  /*------------------------生成每日点名班车-----------------------*/
  const generateDailyDialogOpt = reactive({
      title: '生成每日点名班车',
      fieldList: [
        {field_id: 'date_begin',label: '有效日期起',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3,required: true },
        {field_id: 'date_end',label: '有效日期止',type: 'date',dateFormat: 'YYYY-MM-DD',col: 3 ,required: true},
        {field_id: 'generate_mode',label: '生成模式',type: 'radio',col: 3 ,options: [{name:'只新增',id: '1'},{name: '只修改',id: '2'},{name: '新增和修改',id: '3'}],required: true},
      ],
      data: {generate_mode: '1'},
    }),
    generateDailyDialogRef = ref(null),
    showGenerateDailyDialog = ref(false);
  function generateDailyConfirm(obj) {
    let {date_begin,date_end,generate_mode} = obj.data;
    let dateArray = getDatesInRange(date_begin,date_end);
    progressRef.value.setProgress('loading','正在生成中');
    errmsg.length = 0;
    dateArray = dateArray.map(item =>{
      return {date: item,generate_mode}
    })
    eachRequest(dateArray,0,generateRollCallBasicShuttleByDate,(res,index) =>{
      progressRef.value.setPercentage(Math.ceil( (index +1)/dateArray.length * 100))
      if (res.errcode != 0) {
        errmsg.push(`${dateArray[index]}：${res.errmsg}`);
      }

      // 最后一条数据
      if (index === dateArray.length -1){
        console.log(errmsg);
        let type = '', title = '';
        if(errmsg.length){
          type = 'error';
          title = '生成失败'
        }else {
          type = 'success';
          title = '生成成功';
          showGenerateDailyDialog.value = false;
        }
        progressRef.value.setProgress(type,title,errmsg);
      }
    })
  }


    /*---------------------------------*/

  /**
   * 嵌套循环请求接口
   * @param {Array} arr 所有请求数据集合
   * @param {Number} index 当前请求数据索引
   * @param {Function} requestFn 请求接口
   * @param {Function} callback 回调函数
  */
  const isEachStop = ref(false)
  function eachRequest(arr,index,requestFn,callback) {
    if (isEachStop.value) return;
    if (arr.length < index+1) return
    let data = arr[index];
    console.log(data);
    requestFn && requestFn(data).then(res =>{
      // 错误停止
      if (is_error_stop.value && res.errcode != 0){
        callback && callback(res,index,true);
        return
      }
      callback && callback(res,index);
      eachRequest(arr,index+1,requestFn,callback)
    })
  }


  // 获取日期范围之间的日期集合
  function getDatesInRange(start,end){
    const dateArray = [];
    let curDate = start,
      currentDate = new Date(curDate);

    while (currentDate <= new Date(end)) {
      // 将当前日期的副本推入数组
      dateArray.push(curDate);
      // 将当前日期增加一天
      currentDate.setDate(currentDate.getDate() + 1);
      curDate = crtTimeFtt(currentDate,'YYYY-MM-DD')
    }
    console.log(dateArray);
    return dateArray;
  }

  /*---------------进度条---------------*/
  const progressRef = ref(null),
    errmsg = reactive([])
    /*
    percentage = ref(0),
    duration = computed(() => Math.floor(percentage.value / 5)),
    endError = ref(false),
    progressTitle = ref('正在生成中'),
    stripedFlow = ref(true);
  let showProgress = ref(false)*/;

  /*function setProgress(type,title) {
    showProgress.value = true;
    progressTitle.value = title;
    stripedFlow.value = type === 'loading';
    endError.value = type === 'error';
    // 失败
    if (type === 'success'){
      setTimeout(() =>{
        showProgress.value = false;
      },2000)
    }
    if (type === 'loading'){
      errmsg.length = 0;
    }
  }*/

/*-----------------导入点名班车-----------------*/
  const importData = (file) =>{
    handleUploadChange(file).then(() => getDataList())
  }

  /*--------------照片未上传统计---------------*/
  const showNoUploadTable = ref(false),
    noUploadTableLoading = ref(false),
    noUploadTableData = ref([
      {shuttle_no: '',shuttle_name: '哈哈哈',no_upload_num: 10},
      {shuttle_no: '',shuttle_name: '喝喝喝',no_upload_num: 10}
    ]),
    noUploadTableCols = ref([
      {prop: 'shuttle_no', label: '点名班车号',},
      {prop: 'shuttle_name', label: '点名班车名',},
      {prop: 'not_upload_count', label: '照片未上传数',sortable:true},
      {prop: 'uploaded_count', label: '照片已上传数',},
      {prop: 'should_upload_count', label: '照片应上传数',},
    ]);

  const getSummaries = function (param) {
    const { columns, data } = param;
    const sums = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '合计'
        return
      }
      if (index === 2) {
        const values = data.map((item) => Number(item[column.property]))
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)}`
      } else {
        sums[index] = ''
      }
    })

    return sums
  }

  const getNoUploadData = function () {
    showNoUploadTable.value = true;
    noUploadTableLoading.value = true;
    getNotUploadPicCount(query.value).then(res =>{
      noUploadTableLoading.value = false;
      if (res.errcode != 0) {
        noUploadTableData.value = [];
        return
      }
      let data = res.row || [];
      console.log(data);
      noUploadTableData.value = data;
    })

  }

  const uploadPhotos = function (scope) {
    console.log(scope);
    uploadDialogOpt.title = '确定上传该点名班车照片？'
    showUploadDialog.value = true;
    uploadData.value = [scope.row]
    /*ElMessageBox.confirm('确定上传该点名班车照片？', '上传照片', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm') {
          console.log(scope);
        }
      }
    })*/
  }

  /*---------------批量上传照片--------------------*/
  const formatUploadData = (data) =>{
    return new Promise(async resolve => {
      getParameter({id: 'AliyunFaceMaxBatchSize'}).then(res =>{
        let data = res.row[0],
          size = data && data.parameter_value || 10,
          paramArr = [];
        uploadData.value.forEach(item =>{
          let {shuttle_id,not_upload_count} = item;
          if (not_upload_count > 0) {
              let times = Math.ceil(not_upload_count / size);
              for (let i = 0;i < times; i++){
                paramArr.push({shuttle_id, batch_size: size})
              }
          }
        });
        resolve(paramArr);

      })
    })
  }
  const batchUploadPic = function () {
    uploadDialogOpt.title = '确认批量上传照片？'
    showUploadDialog.value = true;
    uploadData.value = noUploadTableData.value;
  }
  const uploadDialogOpt = reactive({
      title: '确认批量上传照片？',
      width: 500,
      fieldList: [
        {field_id: 'is_error_stop',label: '',col: 3,type: 'checkbox',options: [{name:'错误后停止',id: true}]},

      ],
      data: {is_error_stop: false},
      bindChange: function (data) {
        //  生成类型变化，更新弹窗字段
        is_error_stop.value = data.is_error_stop[0];

      }
    }),
    is_error_stop = ref(false),
    showUploadDialog = ref(false),  //显示确认上传弹窗标识
    uploadDialogRef = ref(null),    //确认上传弹窗
    isShowStopBtn = ref(false),     // 显示停止按钮标识
    uploadData = ref([]);   // 上传参数集合
  let isUploadStop = ref(false),      // 停止上传标识
    loadingInstance = null;
    //弹窗确认
  const uploadConfirm = async function(obj) {
    showUploadDialog.value = false;

    let dataArr = [];
    await formatUploadData().then(data => dataArr = data || []);
    console.log(dataArr);
    if (!dataArr.length){
      ElMessage.warning('没有需要上传的照片');
      return
    }
    isShowStopBtn.value = true;
    isEachStop.value = false;
    progressRef.value.setProgress('loading','批量上传中');
    errmsg.length = 0;
    //模拟上传接口
    const requestFn = function () {
      return new Promise(resolve => {
        setTimeout(() =>{
          resolve({});
        },1000)
      })
    };


    /*eachUploadPic(dataArr,0, (res, index) => {
      progressRef.value.setPercentage(Math.ceil( (index +1)/dataArr.length * 100))
      // percentage.value = Math.ceil( (index +1)/dataArr.length * 100);
      // if (res.errcode != 0) {
      if (res.errcode) {
        errmsg.push(`${dataArr[index]}：${res.errmsg}`);
      }

      // 最后一条数据
      if (index === dataArr.length -1){
        console.log(errmsg);
        let type = '', title = '';
        if(errmsg.length){
          type = 'error';
          title = '上传失败'
        }else {
          type = 'success';
          title = '上传成功';
        }
        isShowStopBtn.value = false;
        progressRef.value.setProgress(type,title,errmsg);
      }
    })*/
    eachRequest(dataArr,0, uploadAliyunFacePic,(res, index,isErrorEnd) => {
      progressRef.value.setPercentage(Math.ceil( (index +1)/dataArr.length * 100))
      if (res.errcode != 0) {
        errmsg.push(`${dataArr[index].shuttle_id}：${res.errmsg}`);
      }

      // 最后一条数据
      if (index === dataArr.length -1 || isErrorEnd){
        console.log(errmsg);
        let type = '', title = '';
        if(errmsg.length){
          type = 'error';
          title = '上传失败'
        }else {
          type = 'success';
          title = '上传成功';
        }
        isShowStopBtn.value = false;
        isEachStop.value = false;
        progressRef.value.setProgress(type,title,errmsg);
        getNoUploadData();
      }
    })
  }
//  定时查询上传结果
  const checkResult = function (isStop) {
    loadingInstance = ElLoading.service({
      text: '正在上传中，请耐心等待',
      background: '#00000080'
    });
    let error = [],
      i = 0;
    let timer = setInterval(() =>{
        if ([1,3].includes(i)){
          error.push(i);
        }
        i++;
        if (i === 5){
          clearInterval(timer);
          showResult(error);
        }
    },500)
  }
  const showResult = function (error) {
    loadingInstance.close();
    let hArr = []
    if (error.length){
      error.forEach( item =>{
        hArr.push(h('div', null, item))
      })
      ElMessageBox({
        title: '出错提示',
        message: h('p', null, hArr),
        confirmButtonText: '确定'
      })
    }else {
      ElMessage({type: 'success',message: '上传成功'});
    }


  }
  // 循环上传
  const eachUploadPic = function (dataArr,index,callback) {
    if (isUploadStop.value) return;
    if (dataArr.length < index+1) return
    let data = dataArr[index],
      requestFn = function () {
        return new Promise(resolve => {
          setTimeout(() =>{
            resolve({},index);
          },1000)
        })
      };
    requestFn(data).then(res =>{
      callback && callback(res,index);
      eachUploadPic(dataArr,index+1,callback)
    })
  }
  //  停止上传
  const stopUpload = function () {
    isEachStop.value = true;
    // isUploadStop.value = true;
    progressRef.value.setProgress('stop','停止批量上传')
  }


</script>

<style scoped lang="less">
    .errmsg{
        padding: 10px 0;
        color: #ff0000;
    }
    .upload-wrap{
        display: inline-block;
        margin: 0 12px;
        vertical-align: bottom;
    }
    .table-dialog-wrap{
        .table-dialog-header{
            display: flex;
            justify-content: flex-end;
        }
        ::v-deep{
            .el-button{
                margin-bottom: 10px;
            }
            .el-dialog__body{
                padding-top: 0;
            }
        }
    }

</style>
